package com.zheng.cms.admin.activemq.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;


@Service
public class ProducerService {
    /**一对一发送消息*/
    @Autowired
    private JmsTemplate jmsQueueTemplate;
    /**一对多发送消息*/
    @Autowired
    private JmsTemplate jmsTopicTemplate;


    @Autowired
    private Destination defaultTopicDestination;

    /**
     * 一对一发送消息
     * ---------send to jms:null
     * qtp2050907347-20 向队列topic://com.zheng.cms.admin.topic.default发送消息---------------------->test
     * qtp2050907347-15 向队列topic://com.zheng.cms.admin.topic.default发送消息---------------------->test
     * */
    public void sendMessage(Destination destination, final String msg){
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination.toString()+"发送消息---------------------->"+msg);
        jmsQueueTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }


    public void sendMessage(final String msg){
        String destination = jmsQueueTemplate.getDefaultDestinationName();
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination+"发送消息---------------------->"+msg);
        jmsQueueTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

    /**
     * 一对多发送消息
     * 一对多订阅推送消息（Topic模式）生产者代码：
     */

    public void sendMessage2(final String msg) {
        String destination = jmsTopicTemplate.getDefaultDestinationName();
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination+"发送消息---------------------->"+msg);
        jmsTopicTemplate.send(defaultTopicDestination,new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }


}
